package com.blog.user.serviceImpl;


import com.blog.admin.vo.PageVO;
import com.blog.common.utils.Assert;
import com.blog.common.utils.UUIDUtils;
import com.blog.common.vo.JsonResult;
import com.blog.user.mapper.ConsumerMapper;
import com.blog.user.pojo.Consumer;
import com.blog.user.service.ConsumerService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName:ConsumerServiceImpl
 * @Author:wubo
 * @Data:2020/7/31 9:11
 */
@Service
public class ConsumerServiceImpl implements ConsumerService {

    @Autowired
    private ConsumerMapper consumerMapper;

    @Override
    public JsonResult saveConsumer(Consumer consumer) {
        Assert.valid(consumer,"用户信息不能为空！");
        String salt= UUIDUtils.getUUID();
        String base = consumer.getPassword()+salt;
        String password = DigestUtils.md5DigestAsHex(base.getBytes());
        consumer.setPassword(password);
        consumer.setSalt(salt);
        consumer.setNewId();
        Date date = new Date();
        consumer.setCreateTime(date);
        consumer.setUpdateTime(date);
        int rs = consumerMapper.insertConsumer(consumer);
        Assert.decide(rs,"注册失败，请稍后再试！");
        return JsonResult.success();
    }

    @Override
    public JsonResult loginCheck(String ticket) {
        Consumer consumer = consumerMapper.selectByTicket(ticket);
        if(consumer==null){
            return JsonResult.fail(201);
        }
        return JsonResult.success();
    }

    @Override
    public String loginHandle(Map<String, Object> data) {
        Consumer consumer = consumerMapper.selectUserByUsername((String) data.get("username"));
        String salt = consumer.getSalt();
        String inputPassword= (String) data.get("password");
        if(DigestUtils.md5DigestAsHex((inputPassword+salt).getBytes()).equals(consumer.getPassword())) {
            return salt;
        }
        return "用户名或密码错误！";
    }

    @Override
    public JsonResult checkUsername(String username) {
        int rs = consumerMapper.selectCountByUsername(username);
        if(rs==0){
            return JsonResult.success("用户名可用");
        }
        return JsonResult.fail();
    }

    @Override
    public JsonResult getConsumerList(PageVO page, Map<String,String> params){
        PageHelper.startPage(page.getCurrPage(),page.getSize(),"");
        Page<Consumer> consumerList = consumerMapper.findBy(params);
        page.setCurrPage(consumerList.getPageNum());
        page.setTotal(consumerList.getTotal());
        page.setData(consumerList.getResult());
        return JsonResult.success("查询用户成功", page);
    }
}
